package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IRedisService;
import cn.wolfcode.wolf2w.redis.test.RedisByKey;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements IRedisService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void saveRedis(String phone, String code) {
        redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);

    }
    @Override
    public String getRedis(String phone) {
        String code = (String) redisTemplate.opsForValue().get(phone);
        return code;
    }

    @Override
    public String setToken(UserInfo userInfo) {
        //使用UUID生成唯一的令牌
        String token = UUID.randomUUID().toString();
        //将令牌拼接成key，以用户对象为value缓存到redis当中
        String key = RedisByKey.USER_TOKEN.join(token);
        String user = JSON.toJSONString(userInfo);
        redisTemplate.opsForValue().set(key,user, Consts.USER_INFO_TOKEN_VAI_TIME,TimeUnit.MINUTES);
        return token;
    }
    //阅读数加一
    @Override
    public Long incrementRead(String readId) {
        Long increment = redisTemplate.opsForValue().increment(readId);
        return increment;
    }
}
